import axios from "axios"
import router from "../router"
import qs from "qs"
const validateStatus = (status) => {
  return status >= 200 && status < 300
}
axios.defaults.timeout = 16000
axios.defaults.withCredentials = true // 设置允许跨域设置cookie
// 开发环境下给定，生产环境删除
// axios.defaults.baseURL='/apis'
axios.defaults.baseURL =
  process.env.NODE_ENV === "production" ? "/apis" : "/apis"
//axios.defaults.baseURL = "http://81.68.170.132:8082/api"
axios.defaults.validateStatus = validateStatus
axios.defaults.headers["Content-Type"] = "application/json"
axios.defaults.headers["x-requested-with"] = "XMLHttpRequest"
let cancel
const promiseArr = {}
// http request 拦截器
axios.interceptors.request.use(
  (config) => {
    //发起请求时，取消掉当前正在进行的相同请求
    if (promiseArr[config.url]) {
      promiseArr[config.url]("操作取消")
      promiseArr[config.url] = cancel
    } else {
      promiseArr[config.url] = cancel
    }
    config.headers.token = localStorage.getItem("TOKEN") || ""
    if (config.headers["Content-Type"] == "application/x-www-form-urlencoded") {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// http request 拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.data.code === 3) {
      router.push("/login")
      console.log(response.data)
      return Promise.reject(response.data.msg)
    }
    return response
  },
  (error) => {
    return Promise.reject(error.response.data.msg) // 返回接口返回的错误信息
  }
)

export default axios
